<template>
  <div class="base-select" :class="{'is-open': isOpen}">
    <div class="select-header" @click="toggleDropdown">
      <span class="selected-value">{{ selectedLabel }}</span>
      <i class="iconfont icon-arrow-down"></i>
    </div>
    <div class="select-dropdown" v-show="isOpen">
      <div 
        class="select-option" 
        v-for="(option, index) in options" 
        :key="index"
        @click="selectOption(option)"
      >
        {{ option.text }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps({
  options: {
    type: Array,
    required: true,
    default: () => []
  },
  modelValue: {
    type: [String, Number],
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

const isOpen = ref(false)

const selectedLabel = computed(() => {
  const selected = props.options.find(opt => opt.value === props.modelValue)
  return selected ? selected.text : '请选择'
})

const toggleDropdown = () => {
  isOpen.value = !isOpen.value
}

const selectOption = (option) => {
  emit('update:modelValue', option.value)
  isOpen.value = false
}

// 点击外部关闭下拉
const handleClickOutside = (e) => {
  if (!e.target.closest('.base-select')) {
    isOpen.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped lang="less">
.base-select {
  position: relative;
  width: 100%;
  
  .select-header {
    height: 36px;
    padding: 0 12px;
    border: 1px solid var(--bs-border-color);
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    background-color: white;
    transition: all 0.3s;
    font-size: 14px;
    
    &:hover {
      border-color: var(--bs-gray-color);
    }
    
    .selected-value {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .iconfont {
      transition: transform 0.3s;
      font-size: 12px;
      color: var(--bs-gray-color);
    }
  }
  
  &.is-open {
    .select-header {
      border-color: var(--bs-theme-color);
      
      .iconfont {
        transform: rotate(180deg);
      }
    }
  }
  
  .select-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    max-height: 200px;
    overflow-y: auto;
    background-color: white;
    border: 1px solid var(--bs-border-color);
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    z-index: 10;
    margin-top: 4px;
  }
  
  .select-option {
    padding: 8px 12px;
    cursor: pointer;
    transition: all 0.2s;
    font-size: 14px;
    
    &:hover {
      background-color: var(--bs-bg-color);
      color: var(--bs-light-color);
    }
  }
}
</style>
